//张
//播放页
<template>
  <div class="play_page">
    <div
      ref="bgBox"
      class="bg_box"
      :class="[isActive ? 'bg_box_active' : 'bg_box_static']"
    >
      <img src="https://api.ixiaowai.cn/gqapi/gqapi.php" />
      <div class="unfold_box" @click="unfold()">
        <img src="../assets/unfold.png" title="展开歌词" />
      </div>
    </div>
    <div class="top_block">
      <div class="play_block">
        <div class="cover_box">
          <img :src="music_cover_path" alt="" />
        </div>
        <div class="control_box">
          <audio
            autoplay="autoplay"
            ref="playerAudio"
            @timeupdate="update"
            :src="playurl"
          />
          <div
            class="bar_box"
            @mouseenter="isShow = true"
            @mouseout="upBar(), (isShow = false)"
            @mousedown="dragBar($event)"
            @mousemove="moveBar($event)"
            @mouseup="upBar()"
          >
            <div
              class="back_bar"
              ref="backBar"
              @mouseenter="isShow = true"
              @mouseup="upBar()"
            >
              <div
                class="current_bar"
                ref="currentBar"
                @mousedown="dragBar($event), (isShow = true)"
              ></div>
              <span class="bar_point" v-show="isShow"></span>
            </div>
          </div>
          <div class="btn_box">
            <span class="comment" @click="focusComment()"
              ><img src="../assets/comment.png" alt=""
            /></span>
            <span class="previous" @click="preSong()"
              ><img src="../assets/preSong.png" alt=""
            /></span>
            <span class="play" @click="playCurrent()"
              ><img src="../assets/play.png" v-show="isPlay" />
              <img
                src="../assets/pause.png"
                class="pause_img"
                v-show="!isPlay"
              />
            </span>
            <span class="next" @click="nextSong()"
              ><img src="../assets/nextSong.png" alt=""
            /></span>
            <span class="like_collect">
              <span class="like" @click="like()"
                ><img src="../assets/like.png" alt="" v-show="!isStar" />
                <img src="../assets/solidCore.png" alt="" v-show="isStar" />
              </span>
            </span>
          </div>
        </div>
      </div>
      <div class="lyric_block">
        <div class="title_block">
          <h3>{{ music_name }}</h3>
          <span>{{ album_name }}</span>
          <span class="singer">{{ singer_name }}</span>
        </div>
        <ul
          class="lyric_box"
          :class="[isActive ? 'lyric_box_active' : 'lyric_box_static']"
          ref="lyric"
        >
          <li
            @click="playThis(index)"
            :class="{ each: true, choose: index == lyricIndex }"
            v-for="(item, key, index) in currentLyrics"
            :key="key"
          >
            {{ item }}
          </li>
        </ul>
      </div>
    </div>
    <div :class="[isActive ? 'bottom_box_active' : 'bottom_box']">
      <bottom_block
        ref="bottomBlock"
        :commentList="commentList"
        :list="music_list"
      />
    </div>
  </div>
</template>

<script>
import bottom_block from "../components/play_page/bottom_block.vue";
export default {
  name: "play_page",
  components: {
    bottom_block,
  },
  data() {
    return {
      isActive: false, //下拉歌词
      music_cover_path: "",
      music_name: "歌曲名字",
      album_name: "专辑名字",
      singer_name: "歌手名字",
      currentLyrics: [], //歌词列表
      playurl: "",
      value: "", //监听播放时间的value
      lyricIndex: 0, //歌次的key  == 时间
      isShow: false,
      isDown: false, //是否按下进度条
      commentList: [], //评论列表
      music_list: [], //歌曲列表
      isPlay: false,
      pageCnt: 1, //页数
      currentSongId: 0,
      flag: 0, //用来区分请求渲染的标志
      currentSongIndex: 0, //当前播放歌曲下标
      isStar: false, //是否已经收藏
    };
  },
  watch: {
    //歌曲id变化时get请求
    currentSongId: {
      handler() {
        this.isPlay = false;
        //登陆时
        if (sessionStorage.getItem("token")) {
          this.$http
            .get("/song", {
              headers: {
                Authorization:
                  "Bearer " + JSON.parse(sessionStorage.getItem("token")),
              },
              params: {
                songId: this.currentSongId,
              },
            })
            .then((res) => {
              this.music_cover_path = res.data.data.cover;
              this.playurl = res.data.data.playurl;
              this.music_name = res.data.data.name;
              this.singer_name = res.data.data.author;
              this.album_name = res.data.data.album;
              if (res.data.data.isStar == 1) {
                this.isStar = true;
              } else this.isStar = false;

              //歌词处理
              let lyricArr = res.data.data.lyrics.split("[").slice(1);
              let lrcObj = {};
              lyricArr.forEach((item) => {
                let arr = item.split("]");
                let m = parseInt(arr[0].split(":")[0]);
                let s = parseInt(arr[0].split(":")[1]);
                arr[0] = m * 60 + s;
                if (arr[1] != "\n") {
                  lrcObj[arr[0]] = arr[1];
                }
              });
              this.currentLyrics = lrcObj;
            });
        }
        //未登录时
        else {
          this.$http
            .get("/song", {
              params: {
                songId: this.currentSongId,
              },
            })
            .then((res) => {
              this.music_cover_path = res.data.data.cover;
              this.playurl = res.data.data.playurl;
              this.music_name = res.data.data.name;
              this.singer_name = res.data.data.author;
              this.album_name = res.data.data.album;
              if (res.data.data.isStar == 1) {
                this.isStar = true;
              } else this.isStar = false;

              //歌词处理
              let lyricArr = res.data.data.lyrics.split("[").slice(1);
              let lrcObj = {};
              lyricArr.forEach((item) => {
                let arr = item.split("]");
                let m = parseInt(arr[0].split(":")[0]);
                let s = parseInt(arr[0].split(":")[1]);
                arr[0] = m * 60 + s;
                if (arr[1] != "\n") {
                  lrcObj[arr[0]] = arr[1];
                }
              });
              this.currentLyrics = lrcObj;
            });
        }

        //get评论
        this.$http
          .get("/comment", {
            params: {
              type: 1,
              tid: this.currentSongId,
            },
          })
          .then((res) => {
            this.commentList = res.data.data;
          });
        for (let i = 0; i < this.music_list.length; i++) {
          if (this.music_list[i].id == this.currentSongId) {
            this.currentSongIndex = i;
          }
        }
      },
      immediate: true,
    },
    // 使用watch监听当前歌曲进度value的变化处理歌词位置
    value() {
      let i = 0;
      // 循环歌词对象
      for (let key in this.currentLyrics) {
        // key表示歌词对象中的时间，如果key等于歌曲进度value，改变当前歌词进度lyricIndex
        if (+key == this.value) {
          //动态更改正在播放的歌词样式
          this.lyricIndex = i;
          // 当歌词进度大于4，即播放到了第4句歌词，开始滚动
          if (i > 4) {
            this.$refs.lyric.scrollTop = 50 * (i - 4);
          }
        }
        i++;
      }
    },
  },
  created() {
    this.flag = this.$route.query.flag;
    //通过不同页面跳转歌曲列表的渲染
    //flag==1:从专辑页跳转
    if (this.flag) {
      if (this.flag == 1) {
        this.$http
          .get("/album", {
            params: {
              album_id: this.$route.query.thisId,
            },
          })
          .then((res) => {
            this.music_list = res.data.data.list;
            this.pageCnt = this.$route.query.pageCnt;
          });
      }
      // flag==2时为歌单页
      else if (this.flag == 2) {
        this.$http
          .get("/playlist", {
            params: {
              playlist_id: this.$route.query.thisId,
            },
          })
          .then((res) => {
            this.music_list = res.data.data.list;
            this.pageCnt = this.$route.pageCnt;
          });
      }
      //flag==3:从搜索歌曲页跳转
      else if (this.flag == 3) {
        this.pageCnt = Math.ceil(this.$route.query.songCnt / 8);
        this.$http
          .get("/search/song", {
            params: {
              keyword: this.$route.query.keyword,
              limit: 8,
            },
          })
          .then((res) => {
            this.music_list = res.data.data.list;
          });
      }
      //flag==4 个人主页喜欢的歌曲
      else if (this.flag == 4) {
        this.$http
          .get("/user/index/songs/", {
            params: {
              limit: 8,
              page: 1,
              id: this.$route.query.userId,
            },
          })
          .then((res) => {
            this.music_list = res.data.data;
          });
      }
      // flag==5 热歌榜
      else if (this.flag == 5) {
        this.$http.get("/hotsongs/").then((res) => {
          this.music_list = res.data.data;
          this.currentSongId = res.data.data[0].id;
        });
      }
      // flag==6 新歌榜
      else if (this.flag == 6) {
        this.$http.get("/newsongs/").then((res) => {
          this.music_list = res.data.data;
          this.currentSongId = res.data.data[0].id;
        });
      }
    }
    //接受传过来的歌曲id
    this.currentSongId = this.$route.query.songId;
    //get当前播放的歌曲信息
    this.$http
      .get("/song", {
        headers: {
          Authorization:
            "Bearer " + JSON.parse(sessionStorage.getItem("token")),
        },
        params: {
          songId: this.$route.query.songId,
        },
      })
      .then((res) => {
        this.music_cover_path = res.data.data.cover;
        this.playurl = res.data.data.playurl;
        this.music_name = res.data.data.name;
        this.singer_name = res.data.data.author;
        this.album_name = res.data.data.album;
        if (res.data.data.isStar == 1) {
          this.isStar = true;
        } else if (res.data.data.isStar == 0) {
          this.isStar = false;
        }
        //处理歌词 转化成key为时间 value为歌词的对象
        //split("["):以[为分割 把字符串分成字符串数组,这里直接等于把[去掉了
        //slice(1):截取前一个数组中的元素
        let lyricArr = res.data.data.lyrics.split("[").slice(1);
        let lrcObj = {};
        lyricArr.forEach((item) => {
          let arr = item.split("]"); //分割右括号
          //得到的arr为有两个字符串的字符串数组
          //arr === [xx:xx , 歌词]
          //时间换成秒
          let m = parseInt(arr[0].split(":")[0]);
          let s = parseInt(arr[0].split(":")[1]);
          //给arr[0]重新赋值为 秒
          arr[0] = m * 60 + s;
          // 转化成key为时间 value为歌词的对象
          if (arr[1] != "\n") {
            lrcObj[arr[0]] = arr[1];
          }
        });
        //存储数据
        this.currentLyrics = lrcObj;
      });
    //get当前播放歌曲的评论
    this.$http
      .get("/comment", {
        params: {
          type: 1,
          tid: this.$route.query.songId,
        },
      })
      .then((res) => {
        this.commentList = res.data.data;
      });
  },
  methods: {
    // 展开歌词功能
    unfold() {
      this.isActive = !this.isActive;
    },
    //时间更新事件
    //时刻监听并获取歌曲播放的信息
    update() {
      const audio = this.$refs.playerAudio;
      //将时间转换成秒
      let mmTime = audio.currentTime;
      this.value = parseInt(mmTime);
      const backWidth = this.$refs.backBar.offsetWidth;
      let proportion = backWidth / audio.duration;
      this.$refs.currentBar.style.width = mmTime * proportion + "px";
    },
    //点击歌词追踪播放时间
    playThis(index) {
      //获取元素
      let audio = this.$refs.playerAudio;
      // 更改高亮样式
      this.lyricIndex = index;
      // 设置当前时间进行播放
      //Object.keys获取当前数组的key值
      audio.currentTime = Object.keys(this.currentLyrics)[index];
    },
    //播放暂停功能
    playCurrent() {
      this.isPlay = !this.isPlay;
      var audio = this.$refs.playerAudio;
      if (audio.paused) {
        audio.play();
      } else {
        audio.pause();
      }
    },
    //播放上一首
    preSong() {
      if (this.currentSongIndex != 0) {
        this.currentSongId = this.music_list[--this.currentSongIndex].id;
      }
    },
    //播放下一首
    nextSong() {
      if (this.currentSongIndex != this.music_list.length - 1) {
        this.currentSongId = this.music_list[++this.currentSongIndex].id;
      } else if (this.currentSongIndex == 7) {
        if (this.$refs.bottomBlock.currentPage != this.pageCnt) {
          this.pageGet(++this.$refs.bottomBlock.currentPage, this.flag);
          this.currentSongId = this.music_list[0].id;
          this.currentSongIndex = 0;
          this.$refs.bottomBlock.currentSong = 0;
        }
      }
    },
    //将光标聚焦到评论区
    focusComment() {
      window.scrollTo({
        top: 1345,
        behavior: "smooth",
      });
    },

    //拖动进度条
    dragBar(e) {
      this.isDown = true;
      let x = e.offsetX;
      let audio = this.$refs.playerAudio;
      const backWidth = this.$refs.backBar.offsetWidth;
      audio.currentTime = audio.duration * (x / backWidth);
    },
    moveBar(e) {
      if (this.isDown == true) {
        let x = e.offsetX;
        this.$refs.currentBar.style.width = x + "px";
        let audio = this.$refs.playerAudio;
        const backWidth = this.$refs.backBar.offsetWidth;
        audio.currentTime = audio.duration * (x / backWidth);
      }
    },
    upBar() {
      this.isDown = false;
    },
    //通过页码数获取歌曲列表
    pageGet(index, flag) {
      flag = Number(flag);
      switch (flag) {
        //从专辑页获取列表
        case 1:
          this.$http
            .get("/album", {
              params: {
                album_id: this.$route.query.thisId,
              },
            })
            .then((res) => {
              this.music_list = res.data.data.list;
            });
          break;
        //从歌单
        case 2:
          this.$http
            .get("/playlist", {
              params: {
                playlist_id: this.$route.query.thisId,
              },
            })
            .then((res) => {
              this.music_list = res.data.data.list;
            });
          break;
        //从搜索歌曲页获取
        case 3:
          this.$http
            .get("/search/song", {
              params: {
                keyword: this.$route.query.keyword,
                limit: 8,
                page: index,
              },
            })
            .then((res) => {
              this.music_list = res.data.data.list;
            });
          break;
        default:
          break;
      }
    },
    //收藏歌曲
    like() {
      if (sessionStorage.getItem("token")) {
        let data = { id: this.currentSongId };
        this.$http
          .post("/star/song/", data, {
            headers: {
              Authorization:
                "Bearer " + JSON.parse(sessionStorage.getItem("token")),
            },
          })
          .then((res) => {
            alert(res.data.msg);
            if (res.data.code == 20000) {
              this.isStar = !this.isStar;
            }
          });
      } else alert("请先登录!");
    },
  },
};
</script>

<style scoped>
.play_page {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  position: relative;
}
.bg_box {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
  float: left;
  transition: all 0.5s;
}
.bg_box_static {
  height: 754px;
}
.bg_box_active {
  height: 1897px;
}
.bg_box_active img {
  transform: scale(2);
}
.bg_box::after {
  content: "";
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background: #000;
  opacity: 0.5;
}
.bg_box img {
  width: auto;
  height: auto;
  transform: scale(1.5);
  filter: blur(4px);
}
.bg_box_active img {
  transform: scale(2);
}
.top_block {
  display: flex;
  justify-content: center;
  width: 100%;
  position: absolute;
  padding-top: 74px;
}
.play_block {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 598px;
  height: 598px;
  background: url("../assets/album_bg.png");
  border-radius: 40px;
  margin-right: 300px;
}
.cover_box {
  width: 314px;
  height: 314px;
  border-radius: 157px;
  overflow: hidden;
  margin-top: 66px;
}
.cover_box img {
  width: 314px;
  height: 314px;
}
.control_box {
  margin-bottom: 54px;
}
.bar_box {
  display: flex;
  align-items: center;
  height: 40px;
}
.bar_box:hover {
  cursor: pointer;
}
.back_bar {
  display: flex;
  align-items: center;
  width: 530px;
  height: 5px;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.64),
    0px 0px 5px 0px rgba(0, 0, 0, 0.71);
  border-radius: 3px;
  background: rgba(0, 0, 0, 0.7);
  transition: all 0.3s;
  margin: 5px 0;
}

.current_bar {
  width: 0px;
  height: 5px;
  background: #659274;
  border-radius: 3px 0 0 3px;
  transition: all 0.3s;
}
.bar_point {
  width: 8px;
  height: 8px;
  border-radius: 4px;
  background: #fff;
}
.btn_box {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 53px;
  margin-top: 36px;
}
.btn_box span {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 53px;
  overflow: hidden;
}
.btn_box > span:nth-child(1),
.btn_box > span:nth-child(2),
.btn_box > span:nth-child(3),
.btn_box > span:nth-child(4) {
  cursor: pointer;
}
.btn_box > span:nth-child(5) > span {
  cursor: pointer;
}
.btn_box img {
  width: 53px;
  height: 53px;
  filter: drop-shadow(#659274 0 60px);
  transform: translateY(-60px);
}
.btn_box .pause_img {
  width: 45px;
  height: 45px;
}
.btn_box .comment {
  width: 90px;
}
.btn_box .comment img {
  width: 37px;
  height: 37px;
}
.btn_box .like img {
  width: 28px;
  height: 24px;
}
.btn_box .like {
  transition: all 0.3s;
}
.btn_box .like:hover {
  cursor: pointer;
  transform: scale(1.1);
}
.btn_box .like_collect {
  width: 90px;
}
.collect {
  margin-left: 10px;
}
.collect img {
  width: 29px;
  height: 29px;
}
.lyric_block {
  width: 500px;
  padding-right: 200px;
  color: #fff;
  margin-top: 30px;
}
.title_block {
  display: flex;
  justify-content: space-around;
  width: 100%;
  height: 30px;
  margin: 0 auto;
  height: 70px;
}
.title_block h3 {
  font-size: 24px;
  font-family: Microsoft YaHei UI;
  font-weight: bold;
  color: #ffffff;
  line-height: 30px;
  text-align: center;
}
.title_block span {
  font-size: 18px;
  font-family: Microsoft YaHei UI;
  font-weight: bold;
  color: #ffffff;
  line-height: 30px;
  text-align: center;
}
.title_block .singer {
  width: 130px;
}
.lyric_box_static {
  height: 480px;
  overflow: hidden;
}
.lyric_box_active {
  height: 1600px;
  overflow: hidden;
}
.lyric_box {
  position: relative;
  margin-top: 20px;
  font-family: Microsoft YaHei UI;
  font-weight: lighter;
  /*  总是显示滚动条 */
  overflow-y: scroll;
  scroll-behavior: smooth;
  color: #ddd;
  font-size: 10px;
  padding: 5px 10px;
}
.lyric_box > li {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  text-align: center;
  font-size: 18px;
}
.lyric_box .choose {
  height: 60px;
  font-size: 24px;
  font-weight: 700;
}

.each {
  height: 50px;
  font-size: 18px;
}
.each:hover {
  cursor: pointer;
}
/* 修改滚动条样式 */
.lyric_box::-webkit-scrollbar {
  width: 2px;
  height: 8px;
}
/* 滑块部分  */
.lyric_box::-webkit-scrollbar-thumb {
  background-color: #ddd;
}

.unfold_box {
  width: 40px;
  height: 35px;
  overflow: hidden;
  position: absolute;
  bottom: 25px;
  right: 625px;
  z-index: 2;
  /* 上下浮动的动画部分 */
  animation: unfold_box 1.3s ease-in-out 2.7s infinite alternate;
}
@keyframes unfold_box {
  from {
    transform: translate(0, -5px);
  }
  to {
    transform: translate(0, 5px);
  }
}
.unfold_box img {
  width: 40px;
  height: 35px;
  transform: translateY(-40px);
  filter: drop-shadow(#659274 0 40px);
}
.bottom_box {
  margin-top: -20px;
}
.bottom_box_active {
  margin-top: 0;
}
</style>